package dao

import (
	"time"

	"github.com/didi/gendry/scanner"
)

//User user struct
type User struct {
	Id         int       `gorm:"id;pk" json:"id" default:""`
	UserRoleId int       `gorm:"user_role_id" json:"user_role_id" default:""`
	Username   string    `gorm:"username" json:"username" default:""`
	Password   string    `gorm:"password" json:"password" default:""`
	CreateTime time.Time `gorm:"create_time" json:"create_time" default:""`
	ModifyTime time.Time `gorm:"modify_time" json:"modify_time" default:""`
	IsDelete   int       `gorm:"is_delete" json:"is_delete" default:"0"`
	Salt       string    `gorm:"salt" json:"salt" default:""`
	// other
	Navs     string `json:"navs"`
	Auths    string `json:"auths"`
	RoleName string `json:"role_name"`
}

// TableName sets the insert table name for this struct type
func (b User) TableName() string {
	return "user"
}

// Users get user list
func Users(qs *Qs, other Other) (data []User, err error) {
	wh, params := qs.Format()
	others := other.Format()
	rows, err := Query(`
		select a.*,b.navs,b.auths,b.name as role_name 
		from user a 
		left join user_role b 
		on a.user_role_id=b.id 
		`+wh+others, params...)
	if err != nil {
		return
	}
	err = scanner.ScanClose(rows, &data)
	return
}

// User get user
func Usero(qs *Qs) (data User, err error) {
	datas, err := Users(qs, DefaultOther)
	if err != nil {
		return
	}
	if len(datas) == 0 {
		err = NotFound
		return
	}
	data = datas[0]
	return
}
